/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package lab2;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author Mikael Köhlmyr | mikael@kohlmyr.com | http://www.kmyr.net
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws IOException {
        // TODO code application logic here
        // Read the xml file, get accounts arraylist
        // Send arraylist into atm, let atm add to the list
        getAccountList();
    }

    public static ArrayList getAccountList() throws FileNotFoundException, IOException{
        ArrayList<String[]> accounts = new ArrayList<String[]>();
        String[] account = new String[3];
        String file = "accounts.xml";
        String[] patterns = {"<aid>[0-9]+</aid>", "<pin>[a-zA-Z0-9]+</pin>", "<bal>[0-9]+</bal>"};
        Pattern pat;
        Matcher mat;
        FileReader fr = new FileReader (new File(file));
        BufferedReader br = new BufferedReader (fr);

        String line = br.readLine();
        while (line != null) {
            for(int i=0; i < 3; i++){
                pat = Pattern.compile(patterns[i]);
                //System.out.println("Pattern >> " + patterns[i]);
                mat = pat.matcher(line);
                if(mat.find()){
                    int end = mat.group().length() - 6;
                    System.out.println("Match >> " + mat.group().substring(5, end));
                    account[i] = mat.group().substring(5, end);
                    line = br.readLine();
                }
                else if(i != 0){//found parts of an account but something is missing
                    System.out.println("Error: accounts.xml is not structured correctly");
                    accounts.clear();
                    break;
                }
                else{//didn't find an id, not yet at a useful row.
                    break;
                }
            }
            line = br.readLine();
        }
          br.close();
        return accounts;
    }

}
